package com.online.customerchatserver.thread;


import com.online.customerchatserver.entity.Message;
import com.online.customerchatserver.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;

/**
 * Created by littleheng on 2018/5/2
 */
public class UuidManageThread implements Runnable {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private MessageService messageService;

    @Override
    public void run() {

        this.messageService = SpringApplicationContextHolder.getApplicationContext().getBean(MessageService.class);

        ThreadLock lock = new ThreadLock();

        while (true) {
            if (lock.getOprLock()) {

                System.out.println("uuid得到锁");
                System.out.println(ThreadLock.uuidsQueue);

                if (ThreadLock.uuidsQueue.isEmpty()) {
                    lock.unOprLock();
                } else {

                    System.out.println("哈哈哈，uuid进来啦");

                    List<String[]> uuids = new ArrayList<String[]>();

                    int queueLen = ThreadLock.uuidsQueue.size();
                    for (int i = 0; i < queueLen; i++) {
                        List<Object> list = ThreadLock.uuidsQueue.peek();
                        Message message = ThreadLock.messagesMap.get(list.get(0).toString());
                        if (message != null) {
                            message.setReadStatus(1);
                            ThreadLock.messagesMap.replace(list.get(0).toString(), message);
                        } else {
                            String[] uuid = {list.get(0).toString(), list.get(1).toString()};
                            uuids.add(uuid);
                        }
                        ThreadLock.uuidsQueue.poll();
                    }
                    lock.unOprLock();
                    if (uuids.size() > 0){
                        this.messageService.modifyBatchMessageStatus(uuids);
                    }
                }
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    this.logger.info(e.getMessage(), e);
                }
            }
        }
    }
}